#include "GameModel.h"
#include "GlobalClass.h"


#include <QEventLoop>



GameModel::GameModel(QObject *parent)
    :QObject(parent)
{
    m_bInitOnce = false;
    m_bInitOnceInThread = false;

    m_eGameStatus = Game_Status_NotRunning;
    m_nGameStatusCode = 0;

    m_bLogicalMaster = false;
    m_bRunAtServer = false;
    m_bNetPlay = false;

    m_eGameType = Game_Type_NULL;
    m_nGameRandom = -1;

    m_nPlayerCount = 0;
    m_nMyID = -1;

}

GameModel::~GameModel()
{
}

int GameModel::_InitOnce()
{
    if(m_bInitOnce)
    {
        return 1;
    }
    m_bInitOnce = true;

    qDebug() << "[GameModel]InitOnce over";
    return 0;
}

int GameModel::InitOnceInThread()
{
    if(m_bInitOnceInThread)
    {
        return 1;
    }
    m_bInitOnceInThread = true;

    qDebug() << "[GameModel]InitOnceInThread over";
    return 0;
}

int GameModel::_GameInit(int sr, QVariantMap param)
{
    if(gameStatus() != Game_Status_NotRunning)
    {
        Warning(_T("[!GameModel]上次游戏没有正确结束!!!"));
        return -1;
    }
    else if(gameStatus() == Game_Status_Init)
        return 1;

    emit s_Debug(_T("[GameModel]随机数种子:%1").arg(lmsSrand(sr)));
    m_eGameStatus = Game_Status_Init;

    return 0;
}

GameModel::_GameStatus GameModel::GameBegin()
{
    m_eGameStatus = Game_Status_Running;

    while(1)
    {
        if(GameAdvance() != Game_Status_Running)
            break;
        QEventLoop loop;
        loop.exec();
    }

    /*_GameStatus status = gameStatus();
    qint32 code = m_nGameStatusCode;

    GameOver();
    emit s_GameOver(status, code);
    */

    sl_OverGame(gameStatus(), m_nGameStatusCode);

    return gameStatus();
    //return GameAdvance();
}

int GameModel::_OverGame(_GameStatus status, qint32 code)
{
    if(gameStatus() == Game_Status_NotRunning)
        return -1;

    QString m_strMsg = QString(_T("[GameModel]游戏结束:%1(%2)")).arg(status).arg(code);
    emit s_Message(m_strMsg);

    if(status == Game_Status_Terminated)
    {
        _TerminateGame(status, code);
        return 1;
    }
    else
        return 0;
}
/*
void GameModel::run()
{
    InitOnceInThread();
    if(GameInit(m_nGameRandom) < 0)
    {
        emit s_Critical(_T("[GameModel]游戏初始化失败!"));
        return;
    }
    GameBegin();
    GameOver();
}
*/

